import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';
import 'package:flutter_inapp_purchase/modules.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:toast/toast.dart';
import 'package:www.znpigai.teacher/global_store/state.dart';

import 'http.dart';
import 'nav.dart';

const Map<String, Color> emumMap = const {
  "Objective-C": Color(0xFF438EFF),
  "Perl": Color(0xFF0298C3),
  "Python": Color(0xFF0298C3),
  "JavaScript": Color(0xFFF1E05A),
  "PHP": Color(0xFF4F5D95),
  "R": Color(0xFF188CE7),
  "Lua": Color(0xFFC22D40),
  "Scala": Color(0xFF020080),
  "Swift": Color(0xFFFFAC45),
  "Kotlin": Color(0xFFF18E33),
  "Vue": Colors.black,
  "Ruby": Color(0xFF701617),
  "Shell": Color(0xFF89E051),
  "TypeScript": Color(0xFF2B7489),
  "C++": Color(0xFFF34B7D),
  "CSS": Color(0xFF563C7C),
  "Java": Color(0xFFB07219),
  "C#": Color(0xFF178600),
  "Go": Color(0xFF375EAB),
  "Erlang": Color(0xFFB83998),
  "C": Color(0xFF555555),
};

class Util {
  static bool canUseAi(Map<String, dynamic> userInfo) {
    var accountInfo = userInfo['accountInfo'];
    if (accountInfo == null) {
      return false;
    }

    if (accountInfo['validBillingCardUser'] ||
        accountInfo['validRechargeUser']) {
      return true;
    }

    if (accountInfo['validExperiencePeriod'] && !accountInfo['surpassQuota']) {
      return true;
    }

    return false;
  }

  static String plainText(String text,
      {String defaultText = '', int maxLength = 0}) {
    if (text == null || text.isEmpty) {
      return defaultText;
    }

    String ret = text
        .replaceAll(new RegExp(r'<br>'), '\n')
        .replaceAll(new RegExp(r'<.*?>'), '')
        .replaceAll('&nbsp;', ' ')
        .replaceAll('&lsquo;', '“')
        .replaceAll('&rsquo;', '”')
        .replaceAll('&ldquo;', '“')
        .replaceAll('&rdquo;', '”')
        .replaceAll('&hellip;', '…')
        .replaceAll('&mdash;', '—');

    if (maxLength > 0 && ret.length > maxLength) {
      ret = ret.substring(0, maxLength);
    }

    return ret;
  }

  static String getTimeDuration(String comTime) {
    var nowTime = DateTime.now();
    var compareTime = DateTime.parse(comTime);
    if (nowTime.isAfter(compareTime)) {
      if (nowTime.year == compareTime.year) {
        if (nowTime.month == compareTime.month) {
          if (nowTime.day == compareTime.day) {
            if (nowTime.hour == compareTime.hour) {
              if (nowTime.minute == compareTime.minute) {
                return '片刻之间';
              }
              return (nowTime.minute - compareTime.minute).toString() + '分钟前';
            }
            return (nowTime.hour - compareTime.hour).toString() + '小时前';
          }
          return (nowTime.day - compareTime.day).toString() + '天前';
        }
        return (nowTime.month - compareTime.month).toString() + '月前';
      }
      return (nowTime.year - compareTime.year).toString() + '年前';
    }
    return 'time error';
  }

  static double setPercentage(percentage, context) {
    return MediaQuery.of(context).size.width * percentage;
  }

  static Color getLangColor(String language) {
    if (emumMap.containsKey(language)) {
      return emumMap[language];
    }
    return Colors.black26;
  }

  static String getTimeDate(String comTime) {
    var compareTime = DateTime.parse(comTime);
    String weekDay = '';
    switch (compareTime.weekday) {
      case 2:
        weekDay = '周二';
        break;
      case 3:
        weekDay = '周三';
        break;
      case 4:
        weekDay = '周四';
        break;
      case 5:
        weekDay = '周五';
        break;
      case 6:
        weekDay = '周六';
        break;
      case 7:
        weekDay = '周日';
        break;
      default:
        weekDay = '周一';
    }
    return '${compareTime.month}-${compareTime.day}  $weekDay';
  }

  static Future<void> showMsgDialog(
      String title, String message, BuildContext context) async {
    // flutter defined function
    return await Alert(
      context: context,
      title: title,
      content: new Text(message),
      buttons: [
        // usually buttons at the bottom of the dialog
        DialogButton(
          color: Colors.blue,
          child: new Text("确定",
              style: TextStyle(color: Colors.white, fontSize: 20)),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ],
    ).show();
  }

  static const OK = 'ok';
  static const CANCEL = 'cancel';

  static Future<bool> showConfirmDialog(
      String title, String message, BuildContext context) async {
    return await Alert(
        context: context,
        title: title,
        content: Text(message),
        buttons: [
          DialogButton(
            onPressed: () => Navigator.pop(context, false),
            child: Text(
              "取消",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          ),
          DialogButton(
            color: Colors.blue,
            onPressed: () => Navigator.pop(context, true),
            child: Text(
              "确定",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
  }

  static Future<String> showInputDialog(String title, String desc,
      String defaultValue, String hint, BuildContext context) async {
    TextEditingController controller =
        TextEditingController(text: defaultValue);

    bool ret = await Alert(
        context: context,
        title: title,
        desc: desc,
        content: Column(
          children: <Widget>[
            TextField(
              decoration: InputDecoration(
                hintText: hint,
              ),
              controller: controller,
            ),
          ],
        ),
        buttons: [
          DialogButton(
            onPressed: () => Navigator.pop(context, false),
            child: Text(
              "取消",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          ),
          DialogButton(
            color: Colors.blue,
            onPressed: () => Navigator.pop(context, true),
            child: Text(
              "确定",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();

    if (ret == true) {
      return controller.text;
    }
    return null;
  }

  static Future<String> showBottomSelectDialog(
      String title, Map<String, String> items, BuildContext context) async {
    List<Widget> itemViews = [];
    items.forEach((k, v) {
      itemViews.add(
          ListTile(title: Text(v), onTap: () => Navigator.of(context).pop(k)));
    });

    return showModalBottomSheet<String>(
        context: context,
        builder: (BuildContext context) {
          return new Column(
              mainAxisSize: MainAxisSize.min, children: itemViews);
        });
  }

  static Future<String> showSelectDialog(
      String title, Map<String, String> items, BuildContext context) async {
    List<Widget> itemViews = [];
    items.forEach((k, v) {
      itemViews.add(
          ListTile(title: Text(v), onTap: () => Navigator.of(context).pop(k)));
    });

    return await showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: Text(title),
          content: SingleChildScrollView(
              child:
                  Column(mainAxisSize: MainAxisSize.min, children: itemViews)),
        );
      },
    );
  }

  static Future<List<String>> showMultiSelectDialog(
      String title,
      Map<String, String> items,
      List<String> selected,
      BuildContext context) async {
    List<Widget> chipWidgets(StateSetter setState) {
      List<Widget> widgets = [];
      items.forEach((k, v) {
        widgets.add(ChoiceChip(
          label: Text(v),
          selected: selected.contains(k),
          selectedColor: Colors.blue,
          onSelected: (state) {
            setState(() {
              if (state) {
                selected.add(k);
              } else {
                selected.remove(k);
              }
            });
          },
        ));
      });
      return widgets;
    }

    bool ok = await Alert(
        context: context,
        title: title,
        content: StatefulBuilder(builder: (context, StateSetter setState) {
          return Wrap(spacing: 10, children: chipWidgets(setState));
        }),
        buttons: [
          DialogButton(
            onPressed: () => Navigator.pop(context, false),
            child: Text(
              "取消",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          ),
          DialogButton(
            color: Colors.blue,
            onPressed: () => Navigator.pop(context, true),
            child: Text(
              "修改",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();

    if (ok == true) {
      return selected;
    }

    return null;
  }

  static showShareDialog(BuildContext context) {
    return showModalBottomSheet<String>(
        context: context,
        builder: (BuildContext context) {
          return new Container(
              height: 160.0,
              child: Stack(
                children: <Widget>[
                  Container(
                    padding: const EdgeInsets.all(10.0),
                    child: Text("分享到", style: TextStyle(fontSize: 12)),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      CupertinoButton(
                          child: Padding(
                              padding: EdgeInsets.all(10.0),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Image.asset("assets/images/weixin_login.png",
                                      width: 50.0,
                                      height: 50.0,
                                      fit: BoxFit.fill),
                                  Text("微信好友", style: TextStyle(fontSize: 12))
                                ],
                              )),
                          onPressed: () {
                            Navigator.of(context).pop("session");
                          }),
                      CupertinoButton(
                          child: Padding(
                              padding: EdgeInsets.all(10.0),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Image.asset("assets/images/wx_ring.png",
                                      width: 50.0,
                                      height: 50.0,
                                      fit: BoxFit.fill),
                                  Text("朋友圈", style: TextStyle(fontSize: 12))
                                ],
                              )),
                          onPressed: () {
                            Navigator.of(context).pop("timeline");
                          }),
                    ],
                  )
                ],
              ));
        });
  }

  Future<String> showCupertino(Action action, BuildContext context) async {
    return await showCupertinoDialog<String>(
        context: context,
        builder: (BuildContext buildContext) {
          return CupertinoAlertDialog(
            title: Text('Are you sure to delete?'),
            actions: <Widget>[
              GestureDetector(
                child: const Text(
                  'Cancel',
                  style: TextStyle(fontSize: 16.0),
                ),
                onTap: () => Navigator.of(buildContext).pop(),
              ),
              GestureDetector(
                child: const Text('Yes', style: TextStyle(fontSize: 16.0)),
                onTap: () => Navigator.of(buildContext).pop(Util.OK),
              )
            ],
          );
        });
  }

  static void alert(String msg, BuildContext context) {
    Toast.show(msg, context, duration: Toast.LENGTH_LONG);
  }

  static void alertFail(HttpResult result, BuildContext context) async {
    if (result.code == 3004) {
      await showMsgDialog('请登录', '您的登录已过期，请重新登录', context);
      GlobalState.isSignIn = false;
      Navigator.of(context).pushNamedAndRemoveUntil(
          GlobalState.isTeacher ? Nav.SOCIAL_LOGIN : Nav.LOGIN,
          (Route<dynamic> route) => false);
    } else if (result.code == 99999) {
      alert("网络请求超时", context);
    } else {
      alert("网络请求失败：${result.errorMsg}", context);
    }
  }

  // 验证订单，并处理购买结果
  static Future<bool> verifyPurchase(BuildContext context,
      PurchasedItem productItem, String wishProductId) async {
    HttpResult result = await Http.post('/correct/pub/api/ios/pay/verify.mvc',
        data: {'verifydata': productItem.transactionReceipt});
    if (!result.success) {
      await Util.showMsgDialog(
          '验证失败', '连接服务器失败：${result.code} ${result.errorMsg}', context);
      return false;
    }

    var data = json.decode(result.data);
    if (data['status'] != 0) {
      await Util.showMsgDialog(
          'AppStore错误', 'AppStore错误：${data['status']}', context);
      return false;
    }

    // 确认支付成功
    var inapp = data['receipt']['in_app'];
    inapp.forEach((purchase) {
      print('>>>> PUR: $purchase');
      if (wishProductId == "" || wishProductId == purchase['product_id']) {
        print('>>>> FINISH: ${purchase['transaction_id']}');
        FlutterInappPurchase.instance
            .finishTransactionIOS(purchase['transaction_id'])
            .then((purResult) {
          print('>>>> P_RES: $purResult');
        });
      }
    });

    await Util.showMsgDialog("支付成功", "点击返回刷新会员详情", context);
    return true;
  }

  static double parsePrice(Object object) {
    if (object is int) {
      return object * 1.0;
    } else if (object is double) {
      return object;
    } else if (object is String) {
      try {
        return double.parse(object);
      } catch (_) {}
    }
    return 0; // 返回0可能导致错误被忽略
  }
}
